package com.mathset.presentation.controller;


import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mathset.bean.Member;
import com.mathset.business.service.IMemberService;
import com.mathset.common.MathsetConstants;

@Controller
@RequestMapping("/user")
public class UserController {

			
	@Autowired
	private IMemberService iMemberService;
	
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public ModelAndView initialUserLoginDialog() {
		return new ModelAndView("login/login").addObject(new Member());
	}
	
	@RequestMapping(value="/validateUser", method=RequestMethod.POST)
	public ModelAndView validateUser(@Valid @ModelAttribute("member")Member member, BindingResult bindingResult,
			HttpSession session) {
		if(!iMemberService.isValidMember(member, bindingResult)) {
			return new ModelAndView("login/login");
		}
		if(member.getEmailStatus() == 0) {
			return new ModelAndView("mail/mail").addObject("email", member.getEmail());
		}
		session.setAttribute(MathsetConstants.MEMBER_ATTRIBUTE, member);
		return new ModelAndView("redirect:/home");
	}
	
	
	@RequestMapping(value="/register", method=RequestMethod.GET)
	public ModelAndView register() {
		return new ModelAndView("login/register").addObject(new Member());
	}
	
	@RequestMapping(value="/validateRegister", method=RequestMethod.POST)
	public ModelAndView validateRegistrion(@Valid @ModelAttribute("member")Member member, BindingResult bindingResult,
			HttpSession session) {
		if(!iMemberService.isValidRegister(member, bindingResult)) {
			return new ModelAndView("login/register");
		}
		iMemberService.addMemberAndMailBox(member);
		session.setAttribute(MathsetConstants.MEMBER_ATTRIBUTE, member);
		return new ModelAndView("redirect:/home");
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public ModelAndView logout(HttpSession session) {
		session.invalidate();
		return new ModelAndView("redirect:/home");
	}
	
//	@RequestMapping(value="/praise", method=RequestMethod.POST)
//	@ResponseBody
//	public String praiseQuestion(@RequestParam( value="id", required=true)String id) {
//		
//		return "success";
//	}
}
